package com.rzrk.centerlogserver.mq;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import org.zeromq.ZMQ;

@Component
public class LogListenEngine {
	Logger log = LoggerFactory.getLogger(getClass());
	
	ZMQ.Context context;
	ZMQ.Socket socket;
	volatile boolean alive;
	Thread thread;
	
	
	@Value("${zmq.url}")
	String url;
	@Resource
	LogStoreManager logStoreManager;
	
	@PostConstruct
	public void start(){
		alive=true;
		context = ZMQ.context(1);
		socket = context.socket(ZMQ.SUB);
		socket.subscribe("".getBytes());
    	socket.bind(url);
    	thread = new Thread(new Runnable() {
			public void run() {
		    	while(alive){
		    		String msg = socket.recvStr();
		        	log.info("recv msg:{}",msg);
		    		logStoreManager.save(msg);
		       }
		    	context.close();
			}
		});
    	thread.start();
    	log.warn("ListenEngine [ok]");
	}
	public void close(){
		alive=false;
		socket.close();
	}
}
